<template>
  <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
    v-model="open" v-if="open" :title="dialogTitle" :fullscreen="true" width="1000" class="dialog1">
    <p class="pinformation" style="margin-top: 10px">搜索条件</p>
    <el-form label-width="80" ref="queryRef" :model="queryParams">
      <el-row>
        <el-col :span="2">
          <el-form-item label="交接批次：" prop="projectCode" label-width="70">
            {{ queryParams.withNumber }}
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="样品编号：" prop="sampleCode">
            <el-input maxlength="100" clearable placeholder="请输入样品编号" v-model="queryParams.sampleCode"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测项目：" prop="jcxmName">
            <el-input maxlength="100" clearable placeholder="请输入检测项目" v-model="queryParams.jcxmName"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="方法编号：" prop="methodCode">
            <el-input maxlength="100" clearable placeholder="请输入方法编号" v-model="queryParams.methodCode"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="质控方式：" prop="sampleType">
            <el-select placeholder="请选择" clearable v-model="queryParams.sampleType" filterable>
              <el-option v-for="dict in proxy.addListNoLimit(qcMethodList)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-row style="padding-bottom: 5px; padding-left: 10px">
            <el-button type="success" @click="handleQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="justify-content: space-between">
      <el-row>
        <p class="pinformation">在库样品列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 15px">
          <!-- v-if="isQc == 0" -->
          <el-button type="success" icon="plus" link @click="handlePwdCode()">批量添加密码样</el-button>
          <el-button type="success" icon="plus" link @click="handleBlind" :disabled="!withId">盲样</el-button>
          <el-button type="success" icon="plus" link @click="handlePxy()" :disabled="!YySJId.length">批量添加平行样</el-button>
          <!-- <el-button type="success" icon="plus" link>查看密码编样表</el-button>
          <el-button type="success" icon="plus" link>查看盲样列表</el-button> -->
          <el-button size="small" type="success" @click="submit" v-if="isQc == 0">提交</el-button>
        </el-row>
      </el-row>
    </el-row>

    <el-table ref="mainTableRef" :data="sampleList" v-loading="loading1" @selection-change="handleSelectionChange"
      row-key="sJId">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="样品编号" align="center" prop="sampleCode" />
      <el-table-column label="检测项目" align="center" prop="jcxmName">
        <template #default="scope">
          <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
        </template>
      </el-table-column>
      <el-table-column label="交接批次" align="center" prop="withNumber" />
      <el-table-column label="方法编号" align="center" prop="methodCode" />
      <el-table-column label="方法名称" align="center" prop="methodName" />
      <el-table-column label="检测点位" align="center" prop="pointName" />
      <el-table-column label="频次" align="center">
        <template #default="scope">
          <template v-if="scope.row.sampleDay">
            第{{ scope.row.sampleDay }}天,第{{ scope.row.sampleCount }}次
          </template>
        </template>
      </el-table-column>
      <el-table-column label="密码样编号" align="center" prop="pwdCode" />
      <el-table-column label="操作" align="center" type="index" width="105" v-if="isQc == 0">
        <template #default="scope">
          <el-button link type="success" v-if="scope.row?.sampleType == 15 || scope.row?.sampleType == 17"
            @click="handleDel(scope.row)">删除</el-button>
          <el-button link type="success" @click="handlePxy(scope.row)" v-else>平行样</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getSampleTable" />
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="bzypOpen" :title="title" width="950px" @close="dialogClose">
      <p class="pinformation">质控样搜索条件</p>
      <el-row>
        <el-col :span="6">
          <el-form-item label="唯一编号：" prop="bzwzCode">
            <el-input maxlength="100" clearable placeholder="请输入唯一编号" v-model="qualityForm.bzwzCode"
              @keyup.enter="handlequalityQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测项目类型：" prop="isSingle" label-width="110">
            <el-select placeholder="请选择" clearable v-model="qualityForm.isSingle" filterable>
              <el-option v-for="dict in sys_bzwz_jcxm_type" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-row style="justify-content: center">
            <el-radio label="0" v-model="qualityForm.isLike">模糊搜索</el-radio>
            <el-radio label="1" v-model="qualityForm.isLike">精准搜索</el-radio>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-row justify="center">
            <el-button type="success" @click="handlequalityQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="handlequalityReset">重置</el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <p class="pinformation">质控样搜索结果列表</p>
        <p class="totalStyle">共 {{ total1 }} 条数据</p>
      </el-row>
      <el-table :data="qualityList" border ref="qualityTable" @row-click="qualityRowClick" height="20vh">
        <el-table-column label="唯一性编号" align="center" prop="bzwzCode" />
        <el-table-column label="标准物质名称" align="center" prop="bzwzName" />
        <el-table-column label="批次号" align="center" prop="produceCode" />
        <el-table-column label="有效日期" align="center" prop="yxDate" />
        <el-table-column label="类型" align="center" prop="bzwzType">
          <template #default="scope">
            <dict-tag :options="sys_bzwz_type" :value="scope.row.bzwzType" />
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <p class="pinformation">检测项目列表</p>
        <p class="totalStyle">共 {{ total2 }} 条数据</p>
      </el-row>
      <el-table :data="qualityJcxmList" border ref="qualityTable" @selection-change="selectionChange" height="20vh">
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="检测项目" align="center" prop="jcxmName">
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="浓度值" align="center" prop="con" />
        <el-table-column label="浓度值单位" align="center" prop="conUnitName" />
        <el-table-column label="不确定度值" align="center" prop="notvalue" />
        <el-table-column label="不确定度单位" align="center" prop="subNotvalueName" />
        <el-table-column label="检测类别" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.jclbId" filterable @change="jclbIdChange(scope.row)">
              <el-option v-for="item in jclbList" :key="item.jclbId" :label="item.jclbName"
                :value="item.jclbId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="检测方法" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.mJId" filterable>
              <el-option v-for="item in scope.row.methodList" :key="item.mJId"
                :label="item.methodCode + '　' + item.methodName" :value="item.mJId">
                <el-tooltip class="box-item" effect="customized" placement="right"
                  :content="item.methodCode + '　' + item.methodName">
                  <div style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    ">
                    {{ item.methodCode + "　" + item.methodName }}
                  </div>
                </el-tooltip>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-row style="justify-content: end">
            <el-form-item label="盲样编号：" prop="methodCode">
              <onlinePreview :typeId="serialTypeId" :paramsData="{ withId: withId }" @emitForm="emitForm"
                ref="onlinePreviewRef"></onlinePreview>
            </el-form-item>
            <!-- :paramsData="{ withId: withId, projectId: props.projectId }" -->
            <el-button type="success" @click="handleDefine" style="margin-left: 15px"
              :disabled="!qualityJcxmIdList.length">确定</el-button>
            <el-button type="danger" @click="bzypOpen = false">关闭</el-button>
          </el-row>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="mmyOpen" title="添加密码样" width="950px" @close="mmyDialogClose">
      <el-row>
        <p class="pinformation">样品列表</p>
        <p class="totalStyle">共 {{ mmyList.length }} 条数据</p>
      </el-row>
      <el-table :data="mmyList" border ref="mmyTable" max-height="50vh" @selection-change="handleMmySelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="交接批次" align="center" prop="withNumber" />
        <el-table-column label="样品编号" align="center" prop="sampleCode" />
        <el-table-column label="密码编号" align="center" prop="pwdCode" />
        <el-table-column label="检测点位" align="center" prop="pointName" />
        <el-table-column label="检测项目" align="center">
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmNames)"></span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" style="margin-left: 15px" :disabled="!ids.length" @click="savePwe">生成密码样编号</el-button>
          <el-button type="danger" @click="delPwe" style="margin-left: 15px" :disabled="!ids.length">删除</el-button>
          <el-button type="danger" @click="mmyOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import onlinePreview from "@/components/onlinePreview/index.vue";
import {
  getSampleList,
  addPxy,
  addPwdCode,
  listQuality,
  listQualityJcxm,
  listJclb,
  listMethod,
  postMethod,
  delPxMy,
  submitQc,
  getId,
  getMmyList,
  savePweCode,
  delPweCode,
} from "@/api/sampleManage/sampleQc";
import bus from "@/utils/eventBus";
const { proxy } = getCurrentInstance();

const { sys_bzwz_type, sys_bzwz_jcxm_type } = proxy.useDict(
  "sys_bzwz_type",
  "sys_bzwz_jcxm_type",
  "sys_degree"
);
const queryParams = ref({ pageNum: 1, pageSize: 10 });
const queryParams1 = ref({ pageNum: 1, pageSize: 10 });
const sampleWithList = ref([]);
const sampleList = ref([]);
const mmyOpen = ref(false);
const qualityList = ref([]);
const qualityJcxmList = ref([]);
const loading = ref(false);
const loading1 = ref(false);
const dialogTitle = ref("");
const title = ref("");
const total = ref(0);
const total1 = ref(0);
const total2 = ref(0);
const mmyList = ref([]);
const open = ref(false);
const bzypOpen = ref(false);
const heightBright = ref("");
const serialTypeId = ref(29);
const onlinePreviewRef = ref(null);
const qualityForm = ref({ isLike: "0" });
const form = ref({ params: {} });
const isQc = ref(1);
function emitForm(val) {
  form.value.params = {};
  form.value.params["serialData"] = val;
}

const qcMethodList = ref([
  { label: "平行样", value: 17 },
  { label: "密码样", value: 13 },
  { label: "盲样", value: 15 },
]);

function getList() {
  loading.value = true;
  queryParams1.value.isQc = props.isQc;
  proxy.resetForm("queryRef");
  heightBright.value = "";
  sampleList.value = [];
  total.value = 0;
  proxy.$refs["mainTableRef"].clearSelection();
}

function handleDefine() {
  form.value.withId = withId.value;
  form.value.bzwzId = bzwzId.value;
  form.value.projectSampleJcxmList = qualityJcxmIdList.value.map((item) => {
    return { 
      bJId: item.bJId, jclbId: item.jclbId, mJId: item.mJId,
      bzwzId: item.bzwzId, bzwzValue: item.con,
      bzwzValueUnit: item.conUnitName,
      bzwzNotvalue: item.notvalue,
      bzwzNotvalueUnit: item.subNotvalueName
    };
  });

  postMethod(form.value).then((res) => {
    bzypOpen.value = false;
    proxy.$modal.msgSuccess("添加成功");
    getSampleTable();
  });
}

const jclbList = ref([]);

function dialogClose() {
  qualityJcxmList.value = [];
  qualityList.value = [];
  qualityForm.value = { isLike: "0" };
  total2.value = 0;
  total1.value = 0;
  bzwzId.value = "";
}

const bzwzId = ref("");

function qualityRowClick(row) {
  proxy.$refs["mainTableRef"].clearSelection();
  listQualityJcxm(row.bzwzId).then((res) => {
    qualityJcxmList.value = res.data;
    total2.value = res.data.length;
    listJclb(withId.value).then((res) => {
      jclbList.value = res.data;
      bzwzId.value = row.bzwzId;
      if (jclbList.value.length == 1) {
        qualityJcxmList.value.forEach((item) => {
          item.jclbId = jclbList.value[0].jclbId;
          listMethod({
            jclbId: jclbList.value[0].jclbId,
            bucketId: item.bucketId,
          }).then((res1) => {
            item.methodList = res1.data;
          });
        });
      }
    });
  });
}

function jclbIdChange(row) {
  row.methodList = [];
  row.mJId = "";
  if (!row.jclbId) return;
  listMethod({ jclbId: row.jclbId, bucketId: row.bucketId }).then((res) => {
    row.methodList = res.data;
  });
}

const withId = ref("");

function getSampleTable() {
  loading1.value = true;
  getSampleList(queryParams.value).then((res) => {
    sampleList.value = res.rows;
    total.value = res.total;
    loading1.value = false;
  });
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.withId = withId.value;
  getSampleTable();
}
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handlequalityQuery() {
  listQuality(qualityForm.value).then((res) => {
    qualityList.value = res.data;
    total1.value = res.data.length;
  });
}
function handlequalityReset() {
  qualityForm.value = { isLike: "0" };
  handlequalityQuery();
}

function handleBlind() {
  bzypOpen.value = true;
  title.value = "盲样";
  listQuality(qualityForm.value).then((res) => {
    qualityList.value = res.data;
    total1.value = res.data.length;
    nextTick(() => {
      onlinePreviewRef.value.getList();
    });
  });
}

const YySJId = ref([]);
function handleSelectionChange(selection) {
  YySJId.value = [];

  selection.forEach((item) => {
    if (item.sampleType != 15 && item.sampleType != 17)
      YySJId.value.push(item.sJId);
  });
}

const qualityJcxmIdList = ref([]);
function selectionChange(selection) {
  qualityJcxmIdList.value = selection;
}

function handlePxy(row) {
  let params = {
    sampleType: 17,
    sJIds: row ? [row.sJId] : YySJId.value,
  };
  addPxy(params).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    getSampleTable();
  });
}

function handlePwdCode(row) {
  mmyOpen.value = true;
  mmyLoading.value = true
  getMmyList({ withId: withId.value }).then((res) => {
    mmyList.value = res.data;
    mmyLoading.value = false
  });
}

function handleDel(row) {
  proxy.$modal.confirm("确认要删除此样品吗？").then(function () {
    delPxMy(row.sJId).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getSampleTable();
    });
  });
}

const heightParams = ref([{ tableName: "main", bottomHeight: 100 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

function selectable(row) {
  if (row.jclbId && row.mJId) {
    return true;
  } else {
    return false;
  }
}

const emit = defineEmits(["sampleClose"]);

function submit() {
  proxy.$modal.confirm("确认要提交吗？").then(function () {
    submitQc({ taskId: taskId.value }).then((res) => {
      proxy.$modal.msgSuccess("提交成功");
      bus.emit("dbSave")
      open.value = false;
    });
  });
}

const taskId = ref("");
function getWithId(taskId1) {
  taskId.value = taskId1;
  getId(taskId1).then((res) => {
    withId.value = res.data.withId;
    handleQuery();
  });
}

function mmyDialogClose(params) {
  mmyList.value = [];
  ids.value = [];
  resetQuery();
}

const ids = ref([]);
function handleMmySelectionChange(selection) {
  ids.value = selection.map((item) => {
    return item.sFIdstr;
  });
}

const mmyLoading = ref(false)

function savePwe() {
  proxy.$modal.confirm("确认要生成密码样编号吗？").then(function () {
    savePweCode({ withId: withId.value, sFIdstrs: ids.value }).then((res) => {
      proxy.$modal.msgSuccess("生成密码样成功！");
      mmyLoading.value = true
      getMmyList({ withId: withId.value }).then((res) => {
        mmyList.value = res.data;
        mmyLoading.value = false
      });
    });
  });
}

function delPwe() {
  proxy.$modal.confirm("确认要删除密码样编号吗？").then(function () {
    delPweCode({ withId: withId.value, sFIdstrs: ids.value }).then((res) => {
      proxy.$modal.msgSuccess("删除密码样编号成功！");
      mmyLoading.value = true
      getMmyList({ withId: withId.value }).then((res) => {
        mmyList.value = res.data;
        mmyLoading.value = false
      });
    });
  });
}

defineExpose({
  open,
  withId,
  handleQuery,
  isQc,
  dialogTitle,
  getWithId,
});
</script>
